package com.heima.wemedia.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.utils.WmThreadLocalUtil;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 查询自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();

        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //分页条件查询
        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        wmNewsLambdaQueryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //频道精确查询
        wmNewsLambdaQueryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //时间范围查询
        wmNewsLambdaQueryWrapper.between(dto.getBeginPubDate() != null && dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        //关键字模糊查询
        wmNewsLambdaQueryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //查询当前用户的文章
        wmNewsLambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        //发布时间倒叙查询
        wmNewsLambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);

        page(wmNewsPage, wmNewsLambdaQueryWrapper);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) wmNewsPage.getTotal());
        responseResult.setData(wmNewsPage.getRecords());
        return responseResult;
    }

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 文章发布
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //0.参数校验
        if (dto == null || dto.getContent() == null) {
            //参数无效
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.保存或者修改文章
        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //封面图片 list->String
        List<String> images = dto.getImages();
        if (images != null && images.size() > 0) {
            String join = StringUtils.join(images, ",");
            wmNews.setImages(join);
        }

        //保存或修改文章
        saveOrUpdateWmNews(wmNews);

        //2.判断是否为草稿,如果为草稿结束当前方法
        if (dto.getStatus() == WmNews.Status.NORMAL.getCode()) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿,保存文章内容图片于素材的关系
        //获取文章内容图片的信息
        List<String> materials = ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials, wmNews.getId());

        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, materials);

        //文章自动审核
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        //发布任务
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * <p>
     * 第二个功能：保存封面图片与素材的关系
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();

        //如果当前封面类型为自动，则设置封面类型的数据
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            //多图
            if (materials.size() >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = images.stream().limit(3).collect(Collectors.toList());
            } else if (materials.size() >= 1 && materials.size() < 3) {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = images.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 处理文章内容于素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片于素材的关系到数据库中
     *
     * @param materials
     * @param newsId
     * @param
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (CollUtil.isNotEmpty(materials)) {
            //1.通过图片的url查询素材
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

            //2.判断素材是否有效
            if (wmMaterials == null || wmMaterials.size() == 0) {
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            if (materials.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            //获取素材ids
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //批量保存文章图片与素材的关系到数据库中
            wmNewsMaterialMapper.saveRelations(ids, newsId, type);

        }
    }

    /**
     * 获取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                list.add(imgUrl);
            }
        }
        return list;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1); //是否上架 默认为1

        if (wmNews.getId() == null) {
            //id不存在-->保存
            save(wmNews);
        } else {
            //id存在-->修改
            //删除文章图片于素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改
            updateById(wmNews);
        }
    }


    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult one(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);

        return ResponseResult.okResult(wmNews);
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //参数校验
        if (id == null) {
            return ResponseResult.errorResult(501, "文章id不可缺少");
        }
        //根据文章id查询文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }

        if (wmNews.getStatus() == 9) {
            return ResponseResult.errorResult(501, "文章已发布不能删除");
        }

        //删除
        wmNewsMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 文章的上架或下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //参数校验
        if (dto.getId() == null) {
            return ResponseResult.errorResult(501, "文章id不可缺少");
        }

        //根据文章id查询该文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(501, "当前文章部署发布状态");
        }

        //文章的上架或下架
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);

        //向kafka发送消息
        Long articleId = wmNews.getArticleId();
        Short enable = wmNews.getEnable();
        Map map = new HashMap();
        map.put("articleId", articleId);
        map.put("enable", enable);
        kafkaTemplate.send("down_or_up", JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
